import 'package:easy_refresh/easy_refresh.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper_null_safety_flutter3/flutter_swiper_null_safety_flutter3.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:my_shop/cache_event_identification.dart';
import 'package:my_shop/load_my_goods.dart';
import 'package:my_shop/silding_goods_list/silding_good_list_page.dart';

class GoodListPage extends StatefulWidget {
  const GoodListPage(
    this.jumpMyPage, {
    super.key,
  });

  final Function jumpMyPage;

  @override
  State<GoodListPage> createState() => _GoodListPageState();
}

class _GoodListPageState extends State<GoodListPage> {
  List<GoodModel> allGoodsList = [];
  List<GoodModel> showList = [];
  List<GoodModel> hotBuyList = [];
  List<GoodModel> hotAddToCartList = [];

  @override
  void initState() {
    super.initState();
    getAllList();
    refreshShowList();
    getHotList();
  }

  void getAllList() {
    allGoodsList = SpUtil.getObjList<GoodModel>(Constant.allGoodsList,
            (v) => GoodModel.fromJson(v as Map<String, dynamic>)) ??
        [];
  }

  void refreshShowList() {
    /// Items with zero stock are not displayed
    showList =
        allGoodsList.where((element) => ((element.stock ?? 0) > 0)).toList();
  }

  void getHotList() {
    hotBuyList = List.from(allGoodsList);
    hotAddToCartList = List.from(allGoodsList);
    hotBuyList.sort((a, b) => a.stock!.compareTo(b.stock!));
    hotAddToCartList.sort((a, b) => b.num!.compareTo(a.num!));
  }

  void refreshPage() {
    setState(() {
      getAllList();
      refreshShowList();
      getHotList();
    });
  }

  @override
  Widget build(BuildContext context) {
    double screenWidth = ScreenUtil.getScreenW(context);

    /// 32 is the outermost margin and 8 is the distance between the two pictures
    double imageWidth = (screenWidth - 32 - 8) / 2;

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Color(SpUtil.getInt(Constant.mainColor) ?? MyColor.mainColor.value),
        title: const Text(
          'Goods',
          textAlign: TextAlign.center,
        ),
        actions: [
          TextButton(
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => SlidingGoodListPage(
                            widget.jumpMyPage,
                            true,
                          )),
                );
              },
              child: const Text('change way to view')),
        ],
      ),
      body: Container(
        padding: const EdgeInsets.all(16),
        child: EasyRefresh(
            onRefresh: () {
              refreshPage();
            },
            child: ListView(
              children: [
                Column(
                  children: [
                    /// Carousel map
                    _buildSwiperImageWidget(),
                    const SizedBox(height: 16),

                    /// Add Hot list
                    _buildTopList(),
                    const SizedBox(height: 16),

                    Wrap(
                      spacing: 8,
                      runSpacing: 8,
                      children: [
                        ...List.generate(
                          showList.length,
                          (index) =>
                              _buildItem(imageWidth, model: showList[index]),
                        )
                      ],
                    )
                  ],
                ),
              ],
            )),
      ),
    );
  }

  /// Individual graph
  Widget _buildItem(double width, {required GoodModel model}) {
    return SizedBox(
      width: width,
      child: Card(
        child: Padding(
          padding: const EdgeInsets.all(6),
          child: Column(
            children: [
              Image.asset(
                model.localUrl ?? '',
                height: 150,
                fit: BoxFit.fitWidth,
              ),
              const SizedBox(
                height: 8,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(model.goodName ?? ''),
                ],
              ),
              const SizedBox(
                height: 8,
              ),
              Row(
                children: [
                  Expanded(
                    child: Wrap(
                      crossAxisAlignment: WrapCrossAlignment.center,
                      children: [
                        Text(
                          '\$ ${(model.price ?? 0.0)}',
                          style: const TextStyle(
                            fontSize: 16,
                            color: Color(0xFFF95757),
                            fontWeight: FontWeight.bold,
                          ),
                          overflow: TextOverflow.ellipsis,
                        ),
                        const SizedBox(
                          width: 5,
                        ),
                        Offstage(
                          offstage: model.marketPrice == null,
                          child: Text(
                            '\$ ${(model.marketPrice ?? 0.0)}',
                            style: const TextStyle(
                              color: Color(0xFF999999),
                              fontSize: 12,
                              decoration: TextDecoration.lineThrough,
                              decorationColor: Color(0xFF999999),
                              decorationThickness: 1,
                            ),
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                      ],
                    ),
                  ),

                  /// add to Cart
                  GestureDetector(
                    onTap: () {
                      if (!(SpUtil.getBool(Constant.isLoginStatus) ?? false)) {
                        widget.jumpMyPage.call();
                        Fluttertoast.showToast(
                            msg:
                                'Currently out of the login state, please login and try again');
                        return;
                      }
                      Fluttertoast.showToast(msg: 'add to cart successful');

                      /// See if the item is in the cache shopping cart list
                      bool thisGoodInCache = false;
                      List<GoodModel>? tempList = SpUtil.getObjList<GoodModel>(
                          Constant.cartModelList, (v) {
                        return GoodModel.fromJson(v as Map<String, dynamic>);
                      });
                      if (tempList?.isNotEmpty == true) {
                        for (int i = 0; i < tempList!.length; i++) {
                          if (tempList[i].goodId == model.goodId) {
                            thisGoodInCache = true;
                            tempList[i].num = (tempList[i].num ?? 0) + 1;
                            SpUtil.putObjectList(
                                Constant.cartModelList, tempList);
                            refreshPage();
                            return;
                          }
                        }
                        if (!thisGoodInCache) {
                          GoodModel tempModel = model;
                          tempModel.num = 1;
                          tempList.add(tempModel);
                          SpUtil.putObjectList(
                              Constant.cartModelList, tempList);
                        }
                      } else {
                        GoodModel tempModel = model;
                        tempModel.num = 1;
                        SpUtil.putObjectList(
                            Constant.cartModelList, [tempModel]);
                      }

                      refreshPage();
                    },
                    child: Image.asset(
                      'assets/images/home/cart.png',
                      fit: BoxFit.cover,
                      height: 20,
                      width: 20,
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// build top list
  Widget _buildTopList() {
    return ClipRRect(
      borderRadius: BorderRadius.circular(8),
      child: Container(
        padding: const EdgeInsets.all(16),
        color: Color(SpUtil.getInt(Constant.mainColor) ?? MyColor.mainColor.value),
        child: Row(
          children: [
            Expanded(
                child: Column(
              children: [
                const Text('Expand the list'),
                ...List.generate(
                    hotAddToCartList.length > 3 ? 3 : hotAddToCartList.length,
                    (index) => _buildEveryTopListItem(
                        index,
                        hotAddToCartList[index].goodName ?? '',
                        hotAddToCartList[index].localUrl ?? '')),
              ],
            )),
            Expanded(
                child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const Text('Hot Buy List'),
                    Image.asset(
                      'assets/images/index/top.png',
                      fit: BoxFit.fill,
                      height: 20,
                      width: 20,
                    ),
                  ],
                ),
                ...List.generate(
                    hotBuyList.length > 3 ? 3 : hotBuyList.length,
                    (index) => _buildEveryTopListItem(
                        index,
                        hotBuyList[index].goodName ?? '',
                        hotBuyList[index].localUrl ?? '')),
              ],
            )),
          ],
        ),
      ),
    );
  }

  Widget _buildEveryTopListItem(int index, String productName, String url) {
    return Padding(
      padding: const EdgeInsets.only(top: 10),
      child: Row(
        children: [
          if (index == 0)
            Stack(
              children: [
                Row(
                  children: [
                    Container(
                      width: 20,
                      height: 20,
                      decoration: const BoxDecoration(
                        shape: BoxShape.circle,
                        color: Color(0xFFFFE3BB),
                      ),
                      child: Center(
                        child: Text(
                          '${index + 1}',
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 14,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                    const SizedBox(width: 8),
                    Text(productName),
                    const SizedBox(width: 6),
                    Image.asset(
                      url,
                      fit: BoxFit.fill,
                      height: 40,
                      width: 40,
                    ),
                  ],
                ),
                Image.asset(
                  'assets/images/index/top.png',
                  fit: BoxFit.fill,
                  height: 20,
                  width: 20,
                ),
              ],
            ),
          if (index != 0)
            Row(
              children: [
                Container(
                  width: 20,
                  height: 20,
                  decoration: const BoxDecoration(
                    shape: BoxShape.circle,
                    color: Color(0xFFFFE3BB),
                  ),
                  child: Center(
                    child: Text(
                      '${index + 1}',
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ),
                const SizedBox(width: 8),
                Text(productName),
                const SizedBox(width: 6),
                Image.asset(
                  url,
                  fit: BoxFit.fill,
                  height: 40,
                  width: 40,
                ),
              ],
            ),
        ],
      ),
    );
  }

  /// Navigation wheel cast chart
  Widget _buildSwiperImageWidget() {
    return SizedBox(
      height: 300,
      child: Swiper(
        /// The initial position of the subscript
        index: 0,
        itemBuilder: (context, index) {
          return GestureDetector(
            onTap: () {},
            child: ClipRRect(
                borderRadius: BorderRadius.circular(8),
                child: SizedBox(
                    height: 300 + 16,
                    child: Image.asset(
                      showList[index].localUrl ?? '',
                      fit: BoxFit.fill,
                    ))),
          );
        },
        itemCount: showList.length,

        /// Set new SwiperPagination() to show the default page indicator
        pagination: SwiperPagination(
          builder: DotSwiperPaginationBuilder(
            size: 6,
            activeSize: 6,
            color: Colors.white.withOpacity(0.5),
            activeColor: Colors.white,
          ),
        ),

        /// Autoplay switch
        autoplay: true,

        duration: 200,

        onTap: (index) {},

        scrollDirection: Axis.horizontal,
      ),
    );
  }
}
